package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderDetailMapper;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkSpaceService;
import com.sky.vo.*;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class ReportServiceImpl implements ReportService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private WorkSpaceService workSpaceService;

    /*
     * 指定日期的营业额的数据统计
     * */
    @Override
    public TurnoverReportVO getTurnoverReport(LocalDate beginTime, LocalDate endTime) {
        /*
         * 从订单表中查询指定日期的订单的总金额
         * */
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(beginTime);
        while (!beginTime.equals(endTime)) {
            //日期计算
            beginTime = beginTime.plusDays(1);
            dateList.add(beginTime);
        }
        StringUtils.join(dateList, "，");
        //遍历每一个日期，进行SQL操作查询当日营业额
        List<Double> count = new ArrayList<>();
        for (LocalDate localDate : dateList) {
            //查询指定日期下的营业额：订单列表状态为已完成的订单金额
            LocalDateTime localBeginTime = LocalDateTime.of(localDate, LocalTime.MIN);
            LocalDateTime localEndTime = LocalDateTime.of(localDate, LocalTime.MAX);
            //"SELECT sum(amount) AS amount FROM orders WHERE status = 5 AND order_time >localBeginTime  AND order_time < localEndTime";
            Double turnover = orderMapper.sumByTimeAndStatus(localBeginTime, localEndTime, 5);
            if (turnover == null) turnover = (double) 0;
            count.add(turnover);
        }


        return TurnoverReportVO
                .builder()
                .dateList(StringUtils.join(dateList, ","))
                .turnoverList(StringUtils.join(count, ","))
                .build();
    }

    /*
     * 统计指定区间内每一天的用户数据（总用户和新增用户）
     * */
    @Override
    public UserReportVO statistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end)) {
            //日期计算
            begin = begin.plusDays(1);
            dateList.add(begin);
        }

        //建立两个集合：统计用户总数量和新增用户数量
        List<Integer> newuserlist = new ArrayList<>();
        List<Integer> totaluserlist = new ArrayList<>();

        List<Double> count = new ArrayList<>();
        for (LocalDate localDate : dateList) {

            LocalDateTime localBeginTime = LocalDateTime.of(localDate, LocalTime.MIN);

            LocalDateTime localEndTime = LocalDateTime.of(localDate, LocalTime.MAX);

            Integer total = userMapper.gettotaluser(localBeginTime);
            if (total == null) {
                total = 0;
            }
            totaluserlist.add(total);
            Integer newuser = userMapper.getnewuser(localBeginTime, localEndTime);
            if (newuser == null) {
                newuser = 0;
            }
            newuserlist.add(newuser);
        }

        return UserReportVO
                .builder()
                .dateList(StringUtils.join(dateList, ","))
                .totalUserList(StringUtils.join(totaluserlist, ","))
                .newUserList(StringUtils.join(newuserlist, ","))
                .build();

    }

    @Override
    public OrderReportVO orderStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end)) {
            //日期计算
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        //订单总数：
        Integer Order_count = orderMapper.getOrderCount();
        //有效订单总数
        Integer validOrder_count = orderMapper.getValidOrderCount();
        //订单完成率
        Double complete_count = (double) validOrder_count / Order_count;
        //每天的订单总数
        List<Integer> TotalordersEveryday = new ArrayList<>();
        //每天的有效订单
        List<Integer> TotalValidordersEveryday = new ArrayList<>();

        for (LocalDate localDate : dateList) {

            LocalDateTime localBeginTime = LocalDateTime.of(localDate, LocalTime.MIN);

            LocalDateTime localEndTime = LocalDateTime.of(localDate, LocalTime.MAX);
            //计算每天的订单总数
            Integer total = orderMapper.countEveryday(localBeginTime, localEndTime);
            if (total == null) total = 0;
            TotalordersEveryday.add(total);
            //计算每天的有效订单数
            Integer valid = orderMapper.getValidOrderCountEveryday(localBeginTime, localEndTime);
            if (valid == null) valid = 0;
            TotalValidordersEveryday.add(valid);
        }


        return OrderReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .orderCompletionRate(complete_count)
                .totalOrderCount(Order_count)
                .validOrderCount(validOrder_count)
                .orderCountList(StringUtils.join(TotalordersEveryday, ","))
                .validOrderCountList(StringUtils.join(TotalValidordersEveryday, ","))
                .build();
    }

    /*
     * 商品top10销量统计
     * */
    @Override
    public SalesTop10ReportVO getTop10(LocalDate begin, LocalDate end) {

        LocalDateTime localBeginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime localEndTime = LocalDateTime.of(end, LocalTime.MAX);

        List<GoodsSalesDTO> goodsSalesDTOs = orderMapper.getGoodsSalesEveryday(localBeginTime, localEndTime);
        List<String> nameList = new ArrayList<>();
        List<Integer> countlist = new ArrayList<>();
        if (goodsSalesDTOs != null && goodsSalesDTOs.size() > 0) {
            for (GoodsSalesDTO goodsSalesDTO : goodsSalesDTOs) {
                nameList.add(goodsSalesDTO.getName());
                countlist.add(goodsSalesDTO.getNumber());
            }
        }
        return SalesTop10ReportVO.builder()
                .nameList(StringUtils.join(nameList, ","))
                .numberList(StringUtils.join(countlist, ","))
                .build();
    }

    /*
     *下载文件到Excle文件中
     * */
    @Override
    public void exportBusinessDate(HttpServletResponse httpServletResponse) throws IOException {
        //1.查询数据库，获取营业数据--查询最近三十天的运营数据
        LocalDate end = LocalDate.now();
        LocalDate start = end.minusDays(30);
        BusinessDataVO businessDataVO = workSpaceService.getBunissesData(LocalDateTime.of(start, LocalTime.MIN), LocalDateTime.of(end, LocalTime.MAX));
        //2.利用POI把数据写入到EXCLE文件中
        InputStream In = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");
        //3.通过输出流把excel文件下载到客户端浏览器
        ServletOutputStream outputStream = httpServletResponse.getOutputStream();
        XSSFWorkbook excle = new XSSFWorkbook(In);
        try {

            //获取表格数据标签页
            XSSFSheet sheet = excle.getSheet("Sheet1");
            //填充时间数据
            sheet.getRow(1).getCell(1).setCellValue("时间:" + start + "到" + end);
            //填充营业额
            sheet.getRow(3).getCell(2).setCellValue(businessDataVO.getTurnover().toString());
            //填充订单完成率
            sheet.getRow(3).getCell(4).setCellValue(businessDataVO.getOrderCompletionRate().toString());
            //填充新增用户数
            sheet.getRow(3).getCell(6).setCellValue(businessDataVO.getNewUsers().toString());
            //填充有效订单
            sheet.getRow(4).getCell(2).setCellValue(businessDataVO.getValidOrderCount().toString());
            //平均客单价
            sheet.getRow(4).getCell(4).setCellValue(businessDataVO.getUnitPrice().toString());

            //填充明细数据

            for (int i = 0; i < 30; i++) {
                LocalDate date = start.plusDays(i);
                //查询当天营业数据
                BusinessDataVO businessDataVO1 = workSpaceService.getBunissesData(LocalDateTime.of(date, LocalTime.MIN), LocalDateTime.of(date, LocalTime.MAX));

                sheet.getRow(7+i).getCell(1).setCellValue(String.valueOf(date));

                //填充营业额
                sheet.getRow(7+i).getCell(2).setCellValue(businessDataVO1.getTurnover().toString());

                //填充订单完成率
                sheet.getRow(7+i).getCell(3).setCellValue(businessDataVO1.getOrderCompletionRate().toString());

                //填充新增用户数
                sheet.getRow(7+i).getCell(4).setCellValue(businessDataVO1.getNewUsers().toString());

                //填充有效订单
                sheet.getRow(7+i).getCell(5).setCellValue(businessDataVO1.getValidOrderCount().toString());

                //平均客单价
                sheet.getRow(7+i).getCell(6).setCellValue(businessDataVO1.getUnitPrice().toString());

            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        excle.write(outputStream);
        //关闭资源
        outputStream.close();
        excle.close();

    }
}

